package com.zpz.framework.zpzoauth.service.impl;

import com.zpz.framework.zpzoauth.common.result.ZpzOauthResultMsg;
import com.zpz.framework.zpzoauth.common.result.ZpzOauthResultStatus;
import com.zpz.framework.zpzoauth.common.utils.ZpzOauthBeanUtils;
import com.zpz.framework.zpzoauth.common.utils.ZpzOauthRequestUtil;
import com.zpz.framework.zpzoauth.dao.ZpzOauthFrameMenuMapper;
import com.zpz.framework.zpzoauth.pojo.pe.GetRoleMenuByUserCodePe;
import com.zpz.framework.zpzoauth.pojo.po.FrameMenu;
import com.zpz.framework.zpzoauth.pojo.po.OauthClientDetails;
import com.zpz.framework.zpzoauth.pojo.qo.AddFrameMenuQo;
import com.zpz.framework.zpzoauth.pojo.qo.DeleteFrameMenuQo;
import com.zpz.framework.zpzoauth.pojo.qo.MenuInfoQo;
import com.zpz.framework.zpzoauth.pojo.qo.ModifyFrameMenuQo;
import com.zpz.framework.zpzoauth.pojo.vo.GetMenuVo;
import com.zpz.framework.zpzoauth.pojo.vo.GetRoleMenuByUserCodeVo;
import com.zpz.framework.zpzoauth.service.ZpzOauthFrameMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangpanzhi
 * @description 菜单管理服务实现
 * @create 2019-07-04 15:44
 */
@Service
public class ZpzOauthFrameMenuServiceImpl implements ZpzOauthFrameMenuService {

    @Resource
    private ZpzOauthFrameMenuMapper zpzOauthFrameMenuMapper;
    @Resource
    private ZpzOauthRequestUtil zpzOauthRequestUtil;
    /**
     * 获取菜单树结构信息
     *
     * @param
     * @return
     */
    @Override
    public ZpzOauthResultMsg<List<GetMenuVo>> getMenuList(HttpServletRequest request, String clientId) throws Exception{
        List<GetMenuVo> treeNodes=new ArrayList<>();
        FrameMenu frameMenu=new FrameMenu();
        frameMenu.setDelFlag(0);
        frameMenu.setClientId(clientId);
        List<FrameMenu> frameMenuList = zpzOauthFrameMenuMapper.select(frameMenu);
        if(frameMenuList!=null){
            List<GetMenuVo> list= ZpzOauthBeanUtils.copyListProperties(frameMenuList,GetMenuVo.class);
            //获取根菜单
            List<GetMenuVo> rootNodes=list.stream().filter((GetMenuVo m)->m.getParentId().equals(0)).collect(Collectors.toList());
            rootNodes.sort(new Comparator<GetMenuVo>() {
                @Override
                public int compare(GetMenuVo getMenuVo, GetMenuVo t1) {
                    return getMenuVo.getSortCode().compareTo(t1.getSortCode());
                }
            });
            for (GetMenuVo m :rootNodes){
                buildChildNodes(m,list);
                treeNodes.add(m);
            }
        }
        if(treeNodes==null || treeNodes.size()<=0){
            return ZpzOauthResultMsg.okForData(new ArrayList<GetMenuVo>());
        }
        return ZpzOauthResultMsg.okForData(treeNodes);
    }

    /**
     * 获取菜单树结构信息--绑定子集信息
     *
     * @param
     * @return
     */
    private void buildChildNodes(GetMenuVo node,List<GetMenuVo> allList){
        List<GetMenuVo> children=getChildNodes(node,allList);
        if(children!=null){
            for (GetMenuVo child:children){
                buildChildNodes(child,allList);
            }
            node.setChildMenuList(children);
        }
        children.sort(new Comparator<GetMenuVo>() {
            @Override
            public int compare(GetMenuVo getMenuVo, GetMenuVo t1) {
                return getMenuVo.getSortCode().compareTo(t1.getSortCode());
            }
        });
    }
    /**
     * 获取菜单树结构信息--获取子集信息
     *
     * @param
     * @return
     */
    private List<GetMenuVo> getChildNodes(GetMenuVo pnode,List<GetMenuVo> allList){
        List<GetMenuVo> childNodes=new ArrayList<>();
        for (GetMenuVo n:allList){
            if(pnode.getId().equals(n.getParentId())){
                childNodes.add(n);
            }
        }
        childNodes.sort(new Comparator<GetMenuVo>() {
            @Override
            public int compare(GetMenuVo getMenuVo, GetMenuVo t1) {
                return getMenuVo.getSortCode().compareTo(t1.getSortCode());
            }
        });
        return childNodes;
    }


    /**
     * 获取获取当前用户权限菜单
     * @param
     * @return
     */
    @Override
    public ZpzOauthResultMsg<List<GetRoleMenuByUserCodeVo>> getCurUserRoleMenu(HttpServletRequest request, MenuInfoQo menuInfoQo) throws Exception{
        String ucode = null;
        String roleCode = menuInfoQo.getRoleCode();
        if (StringUtils.isNotBlank(roleCode) || StringUtils.isNotBlank(menuInfoQo.getUserCode())){
            ucode=menuInfoQo.getUserCode();
        } else {
            // 获取当前用户的菜单权限（登录用户）
            Map<String, String> license = ZpzOauthRequestUtil.getLicense(request);
            if (license==null || license.size()==0){
                return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10023);
            }
            ucode = license.get("ucode");
            if (StringUtils.isBlank(ucode)) {
                return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10027);
            }
        }
        String clientId = menuInfoQo.getClientId();
        if (StringUtils.isBlank(clientId)){
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.CLIENTID_NULL_31054);
        }

        List<GetRoleMenuByUserCodeVo> treeNodes=new ArrayList<>();
        List<GetRoleMenuByUserCodePe>  selectMenuList=null;
        OauthClientDetails client = zpzOauthRequestUtil.getClient(clientId);
        if (client.getAccessType()==0||client.getAccessType()==1){
            selectMenuList= zpzOauthFrameMenuMapper.selectRoleMenuByUserCode(ucode,roleCode,clientId);
        }else if (client.getAccessType()==2){
            Long did = StringUtils.isNotBlank(roleCode)?Long.parseLong(roleCode):null;
            selectMenuList= zpzOauthFrameMenuMapper.selectDepartmentMenuByUserCode(ucode,did,clientId);
        }
        List<Integer> ids=new ArrayList<>();
        List<GetRoleMenuByUserCodePe> frameMenuList=new ArrayList<>();
        frameMenuList=selectMenuList.stream().filter(v->{
            boolean flag=!ids.contains(v.getId());
            ids.add(v.getId());
            return flag;
        }).collect(Collectors.toList());

        if(frameMenuList!=null){
            List<GetRoleMenuByUserCodeVo> list= ZpzOauthBeanUtils.copyListProperties(frameMenuList,GetRoleMenuByUserCodeVo.class);
            list=list.stream().filter((GetRoleMenuByUserCodeVo m )->m.getType().equals(1)).collect(Collectors.toList());

            //获取根菜单
            List<GetRoleMenuByUserCodeVo> rootNodes=list.stream().filter((GetRoleMenuByUserCodeVo m)->m.getParentId().equals(0)).collect(Collectors.toList());
            rootNodes.sort(new Comparator<GetRoleMenuByUserCodeVo>() {
                @Override
                public int compare(GetRoleMenuByUserCodeVo getRoleMenuByUserCodeVo, GetRoleMenuByUserCodeVo t1) {
                    return getRoleMenuByUserCodeVo.getSortCode().compareTo(t1.getSortCode());
                }
            });
            for (GetRoleMenuByUserCodeVo m :rootNodes){
                buildRoleMenuChildNodes(m,list);
                treeNodes.add(m);
            }
        }
        if(treeNodes==null || treeNodes.size()<=0){
            return ZpzOauthResultMsg.okForData(new ArrayList<GetRoleMenuByUserCodeVo>());
        }
        return ZpzOauthResultMsg.okForData(treeNodes);
    }
    /**
     * 获取菜单树结构信息--绑定子集信息
     *
     * @param
     * @return
     */
    private void buildRoleMenuChildNodes(GetRoleMenuByUserCodeVo node,List<GetRoleMenuByUserCodeVo> allList){
        List<GetRoleMenuByUserCodeVo> children=getRoleMenuChildNodes(node,allList);
        if(children!=null){
            for (GetRoleMenuByUserCodeVo child:children){
                buildRoleMenuChildNodes(child,allList);
            }
            node.setChildRoleMenuList(children);
            node.setNextLevelsItems(children.size());

            children.sort(new Comparator<GetRoleMenuByUserCodeVo>() {
                @Override
                public int compare(GetRoleMenuByUserCodeVo getRoleMenuByUserCodeVo, GetRoleMenuByUserCodeVo t1) {
                    return getRoleMenuByUserCodeVo.getSortCode().compareTo(t1.getSortCode());
                }
            });
        }else {
            node.setNextLevelsItems(0);
        }
    }
    /**
     * 获取菜单树结构信息--获取子集信息
     *
     * @param
     * @return
     */
    private List<GetRoleMenuByUserCodeVo> getRoleMenuChildNodes(GetRoleMenuByUserCodeVo pnode,List<GetRoleMenuByUserCodeVo> allList){
        List<GetRoleMenuByUserCodeVo> childNodes=new ArrayList<>();
        for (GetRoleMenuByUserCodeVo n:allList){
            if(pnode.getId().equals(n.getParentId())){
                childNodes.add(n);
            }
        }
        childNodes.sort(new Comparator<GetRoleMenuByUserCodeVo>() {
            @Override
            public int compare(GetRoleMenuByUserCodeVo getRoleMenuByUserCodeVo, GetRoleMenuByUserCodeVo t1) {
                return getRoleMenuByUserCodeVo.getSortCode().compareTo(t1.getSortCode());
            }
        });
        return childNodes;
    }





    /**
     * 添加菜单
     * @param request
     * @param addFrameMenuQo
     * @return
     */
    @Override
    public ZpzOauthResultMsg<Boolean> addframemenuinfo(HttpServletRequest request, AddFrameMenuQo addFrameMenuQo){
        Map<String, String> license = ZpzOauthRequestUtil.getLicense(request);
        if (license==null || license.size()==0){
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10023);
        }
        String ucodeLicense = license.get("ucode");
        if (StringUtils.isBlank(ucodeLicense)) {
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10027);
        }
        FrameMenu obj =new FrameMenu();
        //BeanUtils.copyProperties(addFrameMenuQo, obj);
        obj.setClientId(addFrameMenuQo.getClientId());
        obj.setParentId(addFrameMenuQo.getParentId());
        obj.setName(addFrameMenuQo.getName());
        obj.setMethodUrl(addFrameMenuQo.getMethodUrl());
        obj.setLevel(addFrameMenuQo.getLevel());
        obj.setChildLevelsCount(addFrameMenuQo.getChildLevelsCount());
        obj.setIcon(addFrameMenuQo.getIcon());
        obj.setCheckIcon(addFrameMenuQo.getCheckIcon());
        obj.setType(addFrameMenuQo.getType());
        obj.setAccessCode(addFrameMenuQo.getAccessCode());
        obj.setSortCode(addFrameMenuQo.getSortCode());
        obj.setSysFlag(addFrameMenuQo.getSysFlag());
        obj.setRemarks(addFrameMenuQo.getRemarks());

        obj.setCreateBy(ucodeLicense);
        obj.setCreateDate(new Date());
        obj.setUpdateBy(ucodeLicense);
        obj.setUpdateDate(new Date());
        obj.setDelFlag(0);
        Integer result =zpzOauthFrameMenuMapper.insertFrameMenu(obj);
        if(result > 0){
            return ZpzOauthResultMsg.okForData(true);
        }else {
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.ADD_MENU_FAILURE_31051);
        }
    }

    /**
     * 修改菜单
     * @param request
     * @param modifyFrameMenuQo
     * @return
     */
    @Override
    public ZpzOauthResultMsg<Boolean> updateframemenuinfo(HttpServletRequest request, ModifyFrameMenuQo modifyFrameMenuQo) {
        Map<String, String> license = ZpzOauthRequestUtil.getLicense(request);
        if (license==null || license.size()==0){
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10023);
        }
        String ucodeLicense = license.get("ucode");
        if (StringUtils.isBlank(ucodeLicense)) {
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10027);
        }
        Map mapParam1 = new HashMap();
        mapParam1.put("id",modifyFrameMenuQo.getId());
        FrameMenu framemenuinfo = zpzOauthFrameMenuMapper.selectFrameMenu(mapParam1);
        if(framemenuinfo==null)
        {
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.SELECT_MENU_FAILURE_31050);
        }
        FrameMenu obj =new FrameMenu();
        BeanUtils.copyProperties(modifyFrameMenuQo, obj);
        obj.setUpdateDate(new Date());
        obj.setUpdateBy(ucodeLicense);
        Integer ret= zpzOauthFrameMenuMapper.updateFrameMenu(obj);
        if (ret>0){
            return ZpzOauthResultMsg.okForData(true);
        }else{
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.UPDATE_MENU_FAILURE_31052);
        }
    }

    /**
     * 删除菜单
     * @param request
     * @param deleteFrameMenuQo
     * @return
     */
    @Override
    public ZpzOauthResultMsg<Boolean> delframemenuinfo(HttpServletRequest request, DeleteFrameMenuQo deleteFrameMenuQo) {
        Map<String, String> license = ZpzOauthRequestUtil.getLicense(request);
        if (license==null || license.size()==0){
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10023);
        }
        String ucodeLicense = license.get("ucode");
        if (StringUtils.isBlank(ucodeLicense)) {
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.GATE_WAY_10027);
        }
        Map mapParam1 = new HashMap();
        mapParam1.put("id",deleteFrameMenuQo.getId());
        FrameMenu framemenuinfo = zpzOauthFrameMenuMapper.selectFrameMenu(mapParam1);
        if(framemenuinfo==null)
        {
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.SELECT_MENU_FAILURE_31050);
        }
        Map mapParam = new HashMap();
        mapParam.put("id", deleteFrameMenuQo.getId());
        mapParam.put("updateBy", ucodeLicense);
        mapParam.put("updateDate", new Date());
        Integer ret=zpzOauthFrameMenuMapper.deleteFrameMenu(mapParam);
        if (ret>0){
            return ZpzOauthResultMsg.okForData(true);
        }else{
            return ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.DELETE_MENU_FAILURE_31053);
        }
    }


}
